using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using RentalOfCars.Server.Domain.Database;

namespace RentalOfCars.Server.Infrastructure.ClientServerInterface
{
    public class CarsServiceHostInstanceProvider : IInstanceProvider, IContractBehavior
    {
        private readonly IDbAccessor _accessor;

        public CarsServiceHostInstanceProvider(IDbAccessor accessor)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException("accessor");
            }

            _accessor = accessor;
        }

        #region IContractBehavior Members

        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }

        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                          DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.InstanceProvider = this;
        }

        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                        ClientRuntime clientRuntime)
        {
        }

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint,
                                         BindingParameterCollection bindingParameters)
        {
        }

        #endregion

        #region IInstanceProvider Members

        public object GetInstance(InstanceContext instanceContext)
        {
            return new DbAccessSession(_accessor);
        }

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return GetInstance(instanceContext);
        }

        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
        }

        #endregion
    }
}